﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework;

namespace Checkpoint2XNA.Models.Chess
{
    public class King : Model3D
    {
        const float BOX1_WIDTH = .4f;
        const float BOX1_LENGTH = .4f;
        const float BOX1_HEIGHT = 1f;
        const float BOX2_WIDTH = .8f;
        const float BOX2_LENGTH = BOX1_LENGTH;
        const float BOX2_HEIGHT = .2f;
        const float CROSS_OFFSET = .5f;

        public Box Base;
        public Box Cross;

        public King(Vector3 p, float size, ChessSide c): base(p, c)
        {
            Base = new Box(p, size * BOX1_WIDTH, size * BOX1_LENGTH, size * BOX1_HEIGHT, Color);
            Cross = new Box(new Vector3(p.X, p.Y + size * BOX1_HEIGHT * (1 - CROSS_OFFSET), p.Z), size * BOX2_WIDTH, size * BOX2_LENGTH, size * BOX2_HEIGHT, Color);
        }

        public override void MoveTo(Vector3 point)
        {
            var yOffset = Cross.MinCorner.Y - Base.MinCorner.Y;
            Base.MoveTo(point);
            Cross.MoveTo(new Vector3(point.X, point.Y + yOffset, point.Z));
            CenterBottom = point;
        }

        public override Microsoft.Xna.Framework.Color GetColorAt(Microsoft.Xna.Framework.Vector3 point)
        {
            return Color;
        }

        public override Microsoft.Xna.Framework.Vector3 GetNormal(Microsoft.Xna.Framework.Vector3 point)
        {
            if (point.X <= Base.MinCorner.X || point.X > Base.MaxCorner.X)
                return Cross.GetNormal(point);
            else
                return Base.GetNormal(point);
        }

        public override double RayCollide(Microsoft.Xna.Framework.Vector3 origin, Microsoft.Xna.Framework.Vector3 normalVector)
        {
            var inv = new Vector3(1.0f / normalVector.X, 1.0f / normalVector.Y, 1.0f / normalVector.Z);
            var t = Double.MaxValue;
            double temp;
            if ((temp = Base.BetterRayCollide(origin, normalVector, inv)) > 0 && temp < t)
                t = temp;

            if ((temp = Cross.BetterRayCollide(origin, normalVector, inv)) > 0 && temp < t)
                t = temp;

            return t == Double.MaxValue ? -1 : t;
        }
    }
}
